﻿using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.Xml;

namespace RockBus.DataContracts
{
    [DataContract(Namespace = StringConstants.RockBusNamespace)]
    public class ResponseInfo
    {
        private const int DefaultBufferSize = 4 * 1024 * 1024;

        private ResponseInfo()
        {
            this.BufferSize = DefaultBufferSize;
        }

        public ResponseInfo(string id, string responseAction, string responseXml, int bufferSize = DefaultBufferSize)
        {
            this.Id = id;
            this.ResponseAction = responseAction;
            this.ResponseXml = responseXml;
            this.BufferSize = bufferSize;
        }

        [DataMember]
        public string Id { get; set; }

        [DataMember]
        public string ResponseAction { get; set; }

        [DataMember]
        public string ResponseXml { get; set; }

        [DataMember]
        public int BufferSize { get; set; }

        public MessageBuffer CreateResponseBuffer(MessageVersion messageVersion)
        {
            using (StringReader sr = new StringReader(this.ResponseXml))
            using (XmlReader xr = XmlReader.Create(sr))
            {
                Message response = Message.CreateMessage(messageVersion, this.ResponseAction, xr);
                return response.CreateBufferedCopy(this.BufferSize);
            }
        }
    }
}